package com.itheima.test.sealApplicationBeforeUndertakingTheProject;

import com.alibaba.fastjson.JSONObject;
import com.itheima.enums.NoDrawingsApproveEnum;
import com.itheima.enums.UserRoleEnum;
import com.itheima.pojo.ApproverEnum;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.Process;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricActivityInstanceQuery;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

//项目承接前用章申请
@RunWith(SpringRunner.class)
@SpringBootTest
public class SealApplicationBeforeUndertakingTheProject {

    public Map getVaribales() {
            Map<String, Object> variables = new HashMap<>();
            // variables.put(NoDrawingsApproveEnum.INITIATOR.value,Arrays.asList("initiator"));
            variables.put(NoDrawingsApproveEnum.COMMERCIALTENDERCHECKER.getValue(),Arrays.asList("commercialTenderChecker"));
            variables.put(NoDrawingsApproveEnum.TECHNICALTENDERREVIEWER.getValue(),Arrays.asList("technicalTenderReviewer"));
            variables.put(NoDrawingsApproveEnum.DEPARTMENTHEAD.getValue(),Arrays.asList("departmentHead"));
            variables.put(NoDrawingsApproveEnum.PROJECTOPERATIONMANAGEMENTDEPARTMENT.getValue(),Arrays.asList("projectOperationManagementDepartment"));
            variables.put(NoDrawingsApproveEnum.LAWWORKS.getValue(),Arrays.asList("lawWorks1"));
            variables.put(NoDrawingsApproveEnum.PROJECTGENERALCONTRACTING.getValue(),new ArrayList<>());
            variables.put(NoDrawingsApproveEnum.SEALCHAMBER.getValue(),Arrays.asList("sealChamber1","sealChamber2"));
        variables.put(NoDrawingsApproveEnum.MANAGINGDIRECTOR.getValue(),Arrays.asList("managingDirector1","managingDirector2"));
        variables.put(NoDrawingsApproveEnum.PROJECTMANAGER.getValue(),Arrays.asList("projectManager1","projectManager2"));
            return variables;
    }

    /**
     * 流程部署
     */
    @Test
    public void testDeployment() {
//        1、创建ProcessEngine
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
//        2、获取RepositoryServcie
        RepositoryService repositoryService = processEngine.getRepositoryService();
//        3、使用service进行流程的部署，定义一个流程的名字，把bpmn和png部署到数据中
        Deployment deploy = repositoryService.createDeployment()
                .name("项目承接前用章申请")
                .key("项目承接前用章申请")
                //   .addClasspathResource("huiqian/resultsConfirm.bpmn")
                .addClasspathResource("sealApplicationBeforeUndertakingTheProject/sealApplicationBeforeUndertakingTheProject0822.bpmn20.xml")
                // .addClasspathResource("bpmn/evection.png")
                .deploy();

        System.out.println("流程部署id=" + deploy.getId());
        System.out.println("流程部署名字=" + deploy.getName());
        System.out.println("流程部署key=" + deploy.getKey());

    }


    /**
     * 启动流程实例
     * `act_hi_actinst`    流程实例执行历史信息
     * `act_hi_identitylink` 流程参与用户的历史信息
     * `act_hi_procinst`     流程实例的历史信息
     * `act_hi_taskinst`     流程任务的历史信息
     * `act_ru_execution`    流程执行信息
     * `act_ru_identitylink`  流程的正在参与用户信息
     * `act_ru_task`         流程当前任务信息
     */
    @Test
    public void testStartProcess() {
//        1、创建ProcessEngine
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
//        2、获取RunTimeService
        RuntimeService runtimeService = processEngine.getRuntimeService();

        Map varibales = getVaribales();
        // 3、根据流程定义的id启动流程 in_chapter_approval    results_confirm
        ProcessInstance instance = runtimeService.startProcessInstanceByKey(NoDrawingsApproveEnum.SEALAPPLICATIONBEFOREUNDERTAKINGTHEPROJECT.getValue(), varibales);
//        4、输出内容
        System.out.println("流程定义ID：" + instance.getProcessDefinitionId());
        System.out.println("流程实例ID：" + instance.getId());
        System.out.println("当前活动的ID：" + instance.getActivityId());
    }


    //流程循环执行到一个角色，如果是并行节点，需要拿到后面的一个节点
    @Test
    public void test123() {
        String now = "commercialTenderChecker";
        String next = "departmentHead";

        String processId = "946a835e-eaf8-11ec-aa4d-00ff251e0e80";
//        获取引擎
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = processEngine.getTaskService();

        TaskQuery taskQuery = taskService.createTaskQuery().processInstanceId(processId);

        List<Task> list = taskQuery.list();
        if (list == null || list.isEmpty()) {
            return;
        }
      while (list!=null && !list.isEmpty()){
          String taskDefinitionKey = list.get(0).getTaskDefinitionKey();
          if(taskDefinitionKey.equalsIgnoreCase("lawWorks")){
              break;
          }
          for (int i = 0; i < list.size(); i++) {
              Task task = list.get(i);
              try {
                  taskService.complete(task.getId());
              }catch (Exception e){
                  e.printStackTrace();
              }
          }
          taskQuery = taskService.createTaskQuery().processInstanceId(processId);
          list = taskQuery.list();

      }




    }


    /**
     * 完成个人任务
     */
    @Test
    public void completTask() {

        String processId = "d7d8c11f-21bf-11ed-8629-00ff251e0e80";
//        获取引擎
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
//        获取操作任务的服务 TaskService
        TaskService taskService = processEngine.getTaskService();
        TaskQuery taskQuery = taskService.createTaskQuery().processInstanceId(processId);

        //  TaskQuery taskQuery =  taskService.createTaskQuery().processInstanceBusinessKey("100");
        List<Task> list = taskQuery.list();

        // taskService.complete("44a8763c-a42c-11ec-952a-00ff251e0e80");

        Map varis = new LinkedHashMap();
        for (int i = 0; i < list.size(); i++) {
            Task task = list.get(i);

            System.out.println(task.getId());
            System.out.println(task.getName());
            try {
                taskService.complete(task.getId());
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }


    /**
     * 完成任务 单个人
     */
    @Test
    public void compleateOne() {
        //        获取引擎
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
//        获取操作任务的服务 TaskService
        TaskService taskService = processEngine.getTaskService();

    /*    Map map =new HashMap();
        map.put("outcome","nopass");
*/
        taskService.complete("6973555a-e590-11ec-822c-00ff251e0e80");

    }

    /**
     * 查询流程定义
     */
    @Test
    public void queryProcessDefinition() {
//        获取引擎
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
//        获取  Repositoryservice
        RepositoryService repositoryService = processEngine.getRepositoryService();
//        获取ProcessDifinitionQuery对象
        ProcessDefinitionQuery definitionQuery = repositoryService.createProcessDefinitionQuery();
//        查询当前所有的流程定义 ,返回流程定义信息的集合
//        processDefinitionKey（流程定义Key）
//        orderByProcessDefinitionVersion 进行排序
//        desc 倒叙
//        list 查询出所有的内容
        List<ProcessDefinition> definitionList = definitionQuery.processDefinitionKey("myEvection")
                .orderByProcessDefinitionVersion()
                .desc()
                .list();
//        输出信息
        for (ProcessDefinition processDefinition : definitionList) {
            System.out.println("流程定义ID：" + processDefinition.getId());
            System.out.println("流程定义名称:" + processDefinition.getName());
            System.out.println("流程定义Key:" + processDefinition.getKey());
            System.out.println("流程定义版本:" + processDefinition.getVersion());
            System.out.println("流程部署ID:" + processDefinition.getDeploymentId());
        }
    }

    /**
     * 删除流程部署信息
     * `act_ge_bytearray`
     * `act_re_deployment`
     * `act_re_procdef`
     * 当前的流程如果并没有完成，想要删除的话需要使用特殊方式，原理就是 级联删除
     */
    @Test
    public void deleteDeployMent() {
//      获取流程引擎
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
//        通过引擎来获取 RepositoryService
        RepositoryService repositoryService = processEngine.getRepositoryService();
//        通过部署id来删除流程部署信息
        String deploymentId = "12501";
//        repositoryService.deleteDeployment(deploymentId);
        repositoryService.deleteDeployment(deploymentId, true);
    }


    /**
     * 下载 资源文件
     * 方案1： 使用Activiti提供的api，来下载资源文件,保存到文件目录
     * 方案2： 自己写代码从数据库中下载文件，使用jdbc对blob 类型，clob类型数据读取出来，保存到文件目录
     * 解决Io操作：commons-io.jar
     * 这里我们使用方案1，Activiti提供的api：RespositoryService
     */
    @Test
    public void getDeployment() throws IOException {
//         1、得到引擎
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
//        2、获取api，RepositoryService
        RepositoryService repositoryService = processEngine.getRepositoryService();
//        3、获取查询对象 ProcessDefinitionQuery查询流程定义信息
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionKey("myEvection")
                .singleResult();
//        4、通过流程定义信息，获取部署ID
        String deploymentId = processDefinition.getDeploymentId();
//        5、通过RepositoryService ，传递部署id参数，读取资源信息（png 和 bpmn）
//          5.1、获取png图片的流
//        从流程定义表中，获取png图片的目录和名字
        String pngName = processDefinition.getDiagramResourceName();
//        通过 部署id和 文件名字来获取图片的资源
        InputStream pngInput = repositoryService.getResourceAsStream(deploymentId, pngName);
//          5.2、获取bpmn的流
        String bpmnName = processDefinition.getResourceName();
        InputStream bpmnInput = repositoryService.getResourceAsStream(deploymentId, bpmnName);
//        6、构造OutputStream流
        File pngFile = new File("d:/evectionflow01.png");
        File bpmnFile = new File("d:/evectionflow01.bpmn");
        FileOutputStream pngOutStream = new FileOutputStream(pngFile);
        FileOutputStream bpmnOutStream = new FileOutputStream(bpmnFile);
//        7、输入流，输出流的转换
        IOUtils.copy(pngInput, pngOutStream);
        IOUtils.copy(bpmnInput, bpmnOutStream);
//        8、关闭流
        pngOutStream.close();
        bpmnOutStream.close();
        pngInput.close();
        bpmnInput.close();
    }

    /**
     * 查看历史信息
     */
    @Test
    public void findHistoryInfo() {
//      获取引擎
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
//        获取HistoryService
        HistoryService historyService = processEngine.getHistoryService();
//        获取 actinst表的查询对象
        HistoricActivityInstanceQuery instanceQuery = historyService.createHistoricActivityInstanceQuery();
//        查询 actinst表，条件：根据 InstanceId 查询
//        instanceQuery.processInstanceId("2501");
//        查询 actinst表，条件：根据 DefinitionId 查询
        instanceQuery.processDefinitionId("myEvection:1:4");
//        增加排序操作,orderByHistoricActivityInstanceStartTime 根据开始时间排序 asc 升序
        instanceQuery.orderByHistoricActivityInstanceStartTime().asc();
//        查询所有内容
        List<HistoricActivityInstance> activityInstanceList = instanceQuery.list();
//        输出
        for (HistoricActivityInstance hi : activityInstanceList) {
            System.out.println(hi.getActivityId());
            System.out.println(hi.getActivityName());
            System.out.println(hi.getProcessDefinitionId());
            System.out.println(hi.getProcessInstanceId());
            System.out.println("<==========================>");
        }
    }


    @Test
    public void deleteDeployment() {
//        获取引擎
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
//        获取repositoryService
        RepositoryService repositoryService = processEngine.getRepositoryService();
//        根据部署id 删除部署信息,如果想要级联删除，可以添加第二个参数，true
        repositoryService.deleteDeployment("1");
    }


    /**
     * 下载流程资源。。。。
     */

    @Test
    public void queryBpmnFile() throws IOException {
//        1、得到引擎
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
//        2、获取repositoryService
        RepositoryService repositoryService = processEngine.getRepositoryService();
//        3、得到查询器：ProcessDefinitionQuery，设置查询条件,得到想要的流程定义
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionKey("pd_749350322484285440").processDefinitionId("pd_749350322484285440:1:4130120")
                .singleResult();
//        4、通过流程定义信息，得到部署ID
        String deploymentId = processDefinition.getDeploymentId();
//        5、通过repositoryService的方法，实现读取图片信息和bpmn信息
//        png图片的流
        //  InputStream pngInput = repositoryService.getResourceAsStream(deploymentId, processDefinition.getDiagramResourceName());
//        bpmn文件的流
        InputStream bpmnInput = repositoryService.getResourceAsStream(deploymentId, processDefinition.getResourceName());
//        6、构造OutputStream流
        //  File file_png = new File("d:/evectionflow01.png");
        File file_bpmn = new File("c:/hui/test1.bpmn");
        FileOutputStream bpmnOut = new FileOutputStream(file_bpmn);
        //    FileOutputStream pngOut = new FileOutputStream(file_png);
//        7、输入流，输出流的转换
        //      IOUtils.copy(pngInput,pngOut);
        IOUtils.copy(bpmnInput, bpmnOut);
//        8、关闭流
        //  pngOut.close();
        bpmnOut.close();
        //     pngInput.close();
        bpmnInput.close();
    }

    /**
     * 获取到所有的节点信息
     */
    @Test
    public void test2() throws Exception {
        //        1、得到引擎
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        RuntimeService runtimeService = processEngine.getRuntimeService();
        RepositoryService repositoryService = processEngine.getRepositoryService();
        //流程定义id
        //
        // 流程部署id=1075fcdc-86f5-11ec-bcb7-00ff251e0e80
        //   流程部署名字=成果确认申请流程22                                                                           0a295eb9-8658-11ec-8271-00ff251e0e80
        String processDefinitionId = runtimeService.createProcessInstanceQuery().processDefinitionId("1075fcdc-86f5-11ec-bcb7-00ff251e0e80").singleResult().getProcessDefinitionKey();
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
        Process process = bpmnModel.getProcesses().get(0);
//获取所有节点
        List<UserTask> userTaskList = process.findFlowElementsOfType(UserTask.class);

        for (int i = 0; i < userTaskList.size(); i++) {
            UserTask userTask = userTaskList.get(i);
            System.out.println(userTask.getName());
        }

    }


    //获取到所有的任务 并且执行完成
    @Test
    public void testGetAllAndWancheng() {
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
//        获取操作任务的服务 TaskService
        TaskService taskService = processEngine.getTaskService();
        TaskQuery taskQuery = taskService.createTaskQuery();
        //.processInstanceId("dd94cbc1-8983-11ec-bf40-00ff251e0e80");
        List<Task> list = taskQuery.list();
        for (int i = 0; i < list.size(); i++) {
            Task task = list.get(i);
            taskService.complete(task.getId());
        }
    }


    @Test
    public void testHaha() {

        String json = "{\"flows\":[{\"num\":0,\"enable\":true,\"enale\":true,\"locked\":false,\"nodeType\":\"audit\",\"pos\":1,\"formEdit\":\"no\",\"procInsId\":\"\",\"approvalOrder\":\"sequence\",\"roleType\":\"page\",\"operateType\":\"projectRole\",\"approvalSetting\":\"select\",\"bussinessId\":1,\"flowHandleId\":1,\"type\":\"in_chapter_approval\",\"projectId\":\"-1\",\"projectName\":\"国贸cbd\",\"createBy\":418543349070561281,\"updateBy\":418543349070561281,\"notes\":\"审批意见\",\"performerId\":429210515106955265,\"post\":[{\"bussType\":\"task\",\"id\":\"767107247930085376\",\"key\":\"proj_she_ji_zhu_chi_ren\",\"name\":\"设计主持人\",\"dep\":\"-1\",\"depKey\":\"\",\"sys\":\"\"}],\"title\":\"设计单位(签字/章)\",\"users\":[{\"uid\":\"7\",\"roleId\":null,\"roleKey\":\"zhuanye_fuze_ren\",\"depId\":null,\"depKey\":null,\"userName\":\"佘颖\",\"operateType\":null,\"nodeNum\":null}],\"capacity\":{\"return1\":true,\"turnto\":false,\"withdraw\":false,\"approvalType\":\"0\",\"isStarter\":false},\"tips\":null,\"bussType\":\"生产\",\"uuid\":\"83f5214d-7def-401a-9967-e5e2b76a826c\",\"lastnode\":true,\"lastconts\":false,\"usersinfo\":[],\"hui_qian_ren_info\":[{\"uid\":\"8\",\"roleId\":null,\"roleKey\":\"\",\"depId\":null,\"depKey\":null,\"userName\":\"佘颖\",\"operateType\":null,\"nodeNum\":null,\"majorId\":1,\"majorName\":\"给排水\"},{\"uid\":\"9\",\"roleId\":null,\"roleKey\":\"\",\"depId\":null,\"depKey\":null,\"userName\":\"佘颖\",\"operateType\":null,\"nodeNum\":null,\"majorId\":1,\"majorName\":\"给排水\"}],\"height\":\"50px\",\"userIndex\":\"1-1\",\"blankData\":false}]}";

        JSONObject object = JSONObject.parseObject(json);
        List<JSONObject> lists = (List<JSONObject>) object.get("flows");
        for (int i = 0; i < lists.size(); i++) {
            JSONObject linkedHashMap = lists.get(i);
            Object num = linkedHashMap.get("num");
            System.out.println(num);
        }


    }


    //任务循环完成
    @Test
    public void test22() {
        haha("930308a5-8cc8-11ec-a6cb-00ff251e0e80");
    }


    public void haha(String proinstId) {


        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
//        获取操作任务的服务 TaskService
        TaskService taskService = processEngine.getTaskService();
        TaskQuery taskQuery = taskService.createTaskQuery()
                .processInstanceId(proinstId);
        List<Task> list = taskQuery.list();
        for (int i = 0; i < list.size(); i++) {
            Task task = list.get(i);
            taskService.complete(task.getId());
        }
        taskQuery = taskService.createTaskQuery()
                .processInstanceId(proinstId);
        list = taskQuery.list();
        if (list != null && !list.isEmpty()) {
            haha(proinstId);
        }

    }


    @Test
    public void test23() {


        String detail = "{\"flows\":[{\"num\":1,\"pos\":1,\"post\":[{\"id\":\"767107247930085376\",\"dep\":\"-1\",\"key\":\"proj_she_ji_zhu_chi_ren\",\"sys\":\"\",\"name\":\"设计主持人\",\"depKey\":\"\",\"bussType\":\"task\"}],\"tips\":null,\"type\":\"in_chapter_approval\",\"uuid\":\"83f5214d-7def-401a-9967-e5e2b76a826c\",\"notes\":\"审批意见\",\"title\":\"标题\",\"users\":{\"faqiren\":[{\"uid\":\"7\",\"depId\":null,\"depKey\":null,\"roleId\":null,\"nodeNum\":null,\"roleKey\":\"zhuanye_fuze_ren\",\"userName\":\"佘颖\",\"operateType\":null}],\"tuDangList\":[{\"uid\":\"11\",\"depId\":null,\"depKey\":null,\"roleId\":null,\"nodeNum\":null,\"roleKey\":\"zhuanye_fuze_ren\",\"userName\":\"佘颖\",\"operateType\":null},{\"uid\":\"12\",\"depId\":null,\"depKey\":null,\"roleId\":null,\"nodeNum\":null,\"roleKey\":\"zhuanye_fuze_ren\",\"userName\":\"佘颖\",\"operateType\":null}],\"fuzerenList\":[{\"uid\":\"21\",\"depId\":null,\"depKey\":null,\"roleId\":null,\"nodeNum\":null,\"roleKey\":\"zhuanye_fuze_ren\",\"userName\":\"佘颖\",\"operateType\":null},{\"uid\":\"22\",\"depId\":null,\"depKey\":null,\"roleId\":null,\"nodeNum\":null,\"roleKey\":\"zhuanye_fuze_ren\",\"userName\":\"佘颖\",\"operateType\":null}],\"huiqianList\":[{\"uid\":\"71\",\"depId\":null,\"depKey\":null,\"roleId\":null,\"nodeNum\":null,\"roleKey\":\"zhuanye_fuze_ren\",\"userName\":\"佘颖\",\"operateType\":null,\"majId\":\"1\",\"majName\":\"\"},{\"uid\":\"72\",\"depId\":null,\"depKey\":null,\"roleId\":null,\"nodeNum\":null,\"roleKey\":\"zhuanye_fuze_ren\",\"userName\":\"佘颖\",\"operateType\":null,\"majId\":\"1\",\"majName\":\"\"}],\"shenherenList\":[{\"uid\":\"41\",\"depId\":null,\"depKey\":null,\"roleId\":null,\"nodeNum\":null,\"roleKey\":\"zhuanye_fuze_ren\",\"userName\":\"佘颖\",\"operateType\":null},{\"uid\":\"42\",\"depId\":null,\"depKey\":null,\"roleId\":null,\"nodeNum\":null,\"roleKey\":\"zhuanye_fuze_ren\",\"userName\":\"佘颖\",\"operateType\":null}],\"xiaoduirenList\":[{\"uid\":\"31\",\"depId\":null,\"depKey\":null,\"roleId\":null,\"nodeNum\":null,\"roleKey\":\"zhuanye_fuze_ren\",\"userName\":\"佘颖\",\"operateType\":null},{\"uid\":\"32\",\"depId\":null,\"depKey\":null,\"roleId\":null,\"nodeNum\":null,\"roleKey\":\"zhuanye_fuze_ren\",\"userName\":\"佘颖\",\"operateType\":null}],\"shendingrenList\":[{\"uid\":\"51\",\"depId\":null,\"depKey\":null,\"roleId\":null,\"nodeNum\":null,\"roleKey\":\"zhuanye_fuze_ren\",\"userName\":\"佘颖\",\"operateType\":null},{\"uid\":\"52\",\"depId\":null,\"depKey\":null,\"roleId\":null,\"nodeNum\":null,\"roleKey\":\"zhuanye_fuze_ren\",\"userName\":\"佘颖\",\"operateType\":null}],\"shejizhuchirenList\":[{\"uid\":\"61\",\"depId\":null,\"depKey\":null,\"roleId\":null,\"nodeNum\":null,\"roleKey\":\"zhuanye_fuze_ren\",\"userName\":\"佘颖\",\"operateType\":null},{\"uid\":\"62\",\"depId\":null,\"depKey\":null,\"roleId\":null,\"nodeNum\":null,\"roleKey\":\"zhuanye_fuze_ren\",\"userName\":\"佘颖\",\"operateType\":null}]},\"createBy\":418543349070561281,\"formEdit\":\"no\",\"lastnode\":true,\"nodeType\":\"audit\",\"roleType\":\"page\",\"updateBy\":418543349070561281,\"lastconts\":false,\"procInsId\":\"\",\"projectId\":\"-1\",\"usersinfo\":[],\"bussinessId\":1,\"operateType\":\"projectRole\",\"performerId\":429210515106955265,\"projectName\":\"国贸cbd\",\"flowHandleId\":1,\"approvalOrder\":\"meanwhile\",\"approvalSetting\":\"select\"}]}";
        JSONObject jsonObject = JSONObject.parseObject(detail);

        List<JSONObject> maps = (List<JSONObject>) jsonObject.get("flows");
        JSONObject mapFlow = (JSONObject) maps.get(0);
        JSONObject usersMap = (JSONObject) mapFlow.get("users");
        List<JSONObject> maps1 = (List<JSONObject>) usersMap.get("tuDangList");
        for (int i = 0; i < maps1.size(); i++) {
            System.out.println(maps1.get(i));
        }

        List<String> tuIds = new ArrayList<>();
        for (int i = 0; i < maps1.size(); i++) {
            JSONObject map = maps1.get(i);
            System.out.println(map);
            String uid = (String) map.get("uid");
            tuIds.add(uid);
        }
        Object projectId = mapFlow.get("projectId");
        System.out.println(projectId);

        System.out.println(tuIds.toString());


    }


    @Test
    public void test33() {

        String detail = "{\"flows\":[{\"num\":1,\"pos\":1,\"post\":[{\"id\":\"767107247930085376\",\"dep\":\"-1\",\"key\":\"proj_she_ji_zhu_chi_ren\",\"sys\":\"\",\"name\":\"设计主持人\",\"depKey\":\"\",\"bussType\":\"task\"}],\"tips\":null,\"type\":\"in_chapter_approval\",\"uuid\":\"83f5214d-7def-401a-9967-e5e2b76a826c\",\"notes\":\"审批意见\",\"title\":\"标题\",\"users\":{\"faqiren\":[{\"uid\":\"7\",\"depId\":null,\"depKey\":null,\"roleId\":null,\"nodeNum\":null,\"roleKey\":\"zhuanye_fuze_ren\",\"userName\":\"佘颖\",\"operateType\":null}],\"tuDangList\":[{\"uid\":\"11\",\"depId\":null,\"depKey\":null,\"roleId\":null,\"nodeNum\":null,\"roleKey\":\"zhuanye_fuze_ren\",\"userName\":\"佘颖\",\"operateType\":null},{\"uid\":\"12\",\"depId\":null,\"depKey\":null,\"roleId\":null,\"nodeNum\":null,\"roleKey\":\"zhuanye_fuze_ren\",\"userName\":\"佘颖\",\"operateType\":null}],\"fuzerenList\":[{\"uid\":\"21\",\"depId\":null,\"depKey\":null,\"roleId\":null,\"nodeNum\":null,\"roleKey\":\"zhuanye_fuze_ren\",\"userName\":\"佘颖\",\"operateType\":null},{\"uid\":\"22\",\"depId\":null,\"depKey\":null,\"roleId\":null,\"nodeNum\":null,\"roleKey\":\"zhuanye_fuze_ren\",\"userName\":\"佘颖\",\"operateType\":null}],\"huiqianList\":[{\"uid\":\"71\",\"depId\":null,\"depKey\":null,\"roleId\":null,\"nodeNum\":null,\"roleKey\":\"zhuanye_fuze_ren\",\"userName\":\"佘颖\",\"operateType\":null,\"majId\":\"1\",\"majName\":\"\"},{\"uid\":\"72\",\"depId\":null,\"depKey\":null,\"roleId\":null,\"nodeNum\":null,\"roleKey\":\"zhuanye_fuze_ren\",\"userName\":\"佘颖\",\"operateType\":null,\"majId\":\"1\",\"majName\":\"\"}],\"shenherenList\":[{\"uid\":\"41\",\"depId\":null,\"depKey\":null,\"roleId\":null,\"nodeNum\":null,\"roleKey\":\"zhuanye_fuze_ren\",\"userName\":\"佘颖\",\"operateType\":null},{\"uid\":\"42\",\"depId\":null,\"depKey\":null,\"roleId\":null,\"nodeNum\":null,\"roleKey\":\"zhuanye_fuze_ren\",\"userName\":\"佘颖\",\"operateType\":null}],\"xiaoduirenList\":[{\"uid\":\"31\",\"depId\":null,\"depKey\":null,\"roleId\":null,\"nodeNum\":null,\"roleKey\":\"zhuanye_fuze_ren\",\"userName\":\"佘颖\",\"operateType\":null},{\"uid\":\"32\",\"depId\":null,\"depKey\":null,\"roleId\":null,\"nodeNum\":null,\"roleKey\":\"zhuanye_fuze_ren\",\"userName\":\"佘颖\",\"operateType\":null}],\"shendingrenList\":[{\"uid\":\"51\",\"depId\":null,\"depKey\":null,\"roleId\":null,\"nodeNum\":null,\"roleKey\":\"zhuanye_fuze_ren\",\"userName\":\"佘颖\",\"operateType\":null},{\"uid\":\"52\",\"depId\":null,\"depKey\":null,\"roleId\":null,\"nodeNum\":null,\"roleKey\":\"zhuanye_fuze_ren\",\"userName\":\"佘颖\",\"operateType\":null}],\"shejizhuchirenList\":[{\"uid\":\"61\",\"depId\":null,\"depKey\":null,\"roleId\":null,\"nodeNum\":null,\"roleKey\":\"zhuanye_fuze_ren\",\"userName\":\"佘颖\",\"operateType\":null},{\"uid\":\"62\",\"depId\":null,\"depKey\":null,\"roleId\":null,\"nodeNum\":null,\"roleKey\":\"zhuanye_fuze_ren\",\"userName\":\"佘颖\",\"operateType\":null}]},\"createBy\":418543349070561281,\"formEdit\":\"no\",\"lastnode\":true,\"nodeType\":\"audit\",\"roleType\":\"page\",\"updateBy\":418543349070561281,\"lastconts\":false,\"procInsId\":\"\",\"projectId\":\"-1\",\"usersinfo\":[],\"bussinessId\":1,\"operateType\":\"projectRole\",\"performerId\":429210515106955265,\"projectName\":\"国贸cbd\",\"flowHandleId\":1,\"approvalOrder\":\"meanwhile\",\"approvalSetting\":\"select\"}]}";
        JSONObject jsonObject = JSONObject.parseObject(detail);

        Map<String, Object> variables = new HashMap<>();
    /*    variables.put("tu_dang_num",3);
        variables.put("fa_qi_ren","faqiren");

        variables.put("tuDangList",Arrays.asList("tudang1","tudang2"));

        variables.put("fuzerenList",Arrays.asList("fuzeren1","fuzeren2"));
        variables.put("xiaoduirenList",Arrays.asList("xiaodui1","xiaodui2"));
        variables.put("shenherenList",Arrays.asList("shenhe1","shenhe2"));
        variables.put("shendingrenList" ,Arrays.asList("shending1","shending2"));
        variables.put("shejizhuchirenList",Arrays.asList("shenji1","shenji2"));
        variables.put("huiqianList",Arrays.asList("huiqian1","huiqian2"));
        variables.put("huiqianNum",2);*/

        List<JSONObject> mapsFlows = (List<JSONObject>) jsonObject.get("flows");
        JSONObject mapFlow = (JSONObject) mapsFlows.get(0);
        JSONObject usersMap = (JSONObject) mapFlow.get("users");
        List<JSONObject> tuDangList = (List<JSONObject>) usersMap.get(ApproverEnum.tuDangList);
        List<String> tudanguids = getUid(tuDangList);

        List<JSONObject> faqiren = (List<JSONObject>) usersMap.get(ApproverEnum.faqiren);
        List<String> faqirenIds = getUid(faqiren);


        List<JSONObject> fuzerenList = (List<JSONObject>) usersMap.get(ApproverEnum.fuzerenList);
        List<String> fuzerenIds = getUid(fuzerenList);

        List<JSONObject> huiqianList = (List<JSONObject>) usersMap.get(ApproverEnum.huiqianList);
        List<String> huiqianIds = getUid(huiqianList);

        List<JSONObject> shejizhuchirenList = (List<JSONObject>) usersMap.get(ApproverEnum.shejizhuchirenList);
        List<String> shejizhuchirenIds = getUid(shejizhuchirenList);

        List<JSONObject> shendingrenList = (List<JSONObject>) usersMap.get(ApproverEnum.shendingrenList);
        List<String> shendingrenIds = getUid(shendingrenList);

        List<JSONObject> shenherenList = (List<JSONObject>) usersMap.get(ApproverEnum.shenherenList);
        List<String> shenherenIds = getUid(shenherenList);

        List<JSONObject> xiaoduirenList = (List<JSONObject>) usersMap.get(ApproverEnum.xiaoduirenList);
        List<String> xiaoduirenIds = getUid(xiaoduirenList);
        // 发起人
        if (faqirenIds != null && !faqirenIds.isEmpty()) {
            variables.put("fa_qi_ren", faqirenIds.get(0));
        }
        //图档人
        if (tuDangList != null && !tuDangList.isEmpty()) {
            variables.put(ApproverEnum.tuDangList, tudanguids);
            variables.put(ApproverEnum.tuDangNum, tuDangList.size());
        } else {
            variables.put(ApproverEnum.tuDangNum, 0);

        }
        //负责人
        variables.put(ApproverEnum.fuzerenList, fuzerenIds);
        // 会签
        if (huiqianIds != null && !huiqianIds.isEmpty()) {
            variables.put(ApproverEnum.huiqianNum, huiqianIds.size());
            variables.put(ApproverEnum.huiqianList, huiqianIds);

        } else {
            variables.put(ApproverEnum.huiqianNum, 0);
        }
        //校对人
        variables.put(ApproverEnum.xiaoduirenList, xiaoduirenIds);
        //审核人
        variables.put(ApproverEnum.shenherenList, shendingrenIds);
        //审定人
        variables.put(ApproverEnum.shendingrenList, shendingrenIds);

        // 设计主持人
        variables.put(ApproverEnum.shejizhuchirenList, shejizhuchirenIds);
        System.out.println(variables);
    }


    public List<String> getUid(List<JSONObject> userList) {
        List<String> uids = new ArrayList<>();
        for (int i = 0; i < userList.size(); i++) {
            JSONObject map = userList.get(i);
            System.out.println(map);
            String uid = (String) map.get("uid");
            uids.add(uid);
        }

        return uids;
    }


    @Test
    public void test11() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        System.out.println(dateString);

    }

    //删除流程

    @Test
    public void deleteDeployment1() {
        // 流程部署id
        String deploymentId = "1";

        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        // 通过流程引擎获取repositoryService
        RepositoryService repositoryService = processEngine
                .getRepositoryService();
        //删除流程定义，如果该流程定义已有流程实例启动则删除时出错

        repositoryService.deleteDeployment("5c77d9eb-a342-11ec-8eb3-00ff251e0e80", true);
        //设置true 级联删除流程定义，即使该流程有流程实例启动也可以删除，设置为false非级别删除方式，如果流

        //repositoryService.deleteDeployment(deploymentId, true);
    }


    /**
     * 9 * 生成 activiti的数据库表
     * 10
     */
    @Test
    public void testCreateDbTable() {
        //使用classpath下的activiti.cfg.xml中的配置创建processEngine
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        System.out.println(processEngine);
    }


    @Test
    public void test1() {
     String msg=  "projectOperationManagementDepartment";
        System.out.println(msg.length());
    }

}
